package uploader

import (
	"bytes"
	"context"
	"github.com/qiniu/api.v7/v7/auth/qbox"
	"github.com/qiniu/api.v7/v7/storage"
	"shop-common/library/variables"
	"strconv"
	"strings"
)

type QiniuUploader struct{}

func NewQiniuUploader() IUploader {
	return &QiniuUploader{}
}

//fmt.Sprintf("%s%s", "http://go.cdbob.cn/", fileInfo.FileName)
/**
图片上传
*/
func (s *QiniuUploader) Put(validFile *FileRequest) (*FileVO, error) {
	bucketName := variables.ZoneSetting.Qiniu.BucketName
	accessKey := variables.ZoneSetting.Qiniu.AccessKey
	secretKey := variables.ZoneSetting.Qiniu.SecretKey

	putPolicy := storage.PutPolicy{
		Scope:   bucketName,
		Expires: 120,
	}

	mac := qbox.NewMac(accessKey, secretKey)
	region, _ := storage.GetRegion(accessKey, bucketName)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{
		//Zone:          &storage.ZoneHuanan,
		Zone:          region,
		UseCdnDomains: false,
		UseHTTPS:      false,
	}
	putExtra := storage.PutExtra{}
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}

	ct := strings.Split(validFile.FileType, "/")

	return &FileVO{
			RealName:     validFile.RealName,
			Name:         validFile.NewFileName,
			AttDir:       "",
			AttSize:      strconv.Itoa(validFile.StreamSize),
			AttType:      ct[len(ct)-1],
			ContentType:  validFile.FileType,
			LocationType: QINIU_TYPE_ATTACHMENT,
			Key:          ret.Key,
			Hash:         ret.Hash,
			Bucket:       bucketName,
		},
		formUploader.Put(context.Background(), &ret, upToken, validFile.NewFileName, bytes.NewBuffer(validFile.FileStream), int64(validFile.StreamSize), &putExtra)
}

func (s *QiniuUploader) Move(oldname, newname string) (string, error) {
	bucketName := variables.ZoneSetting.Qiniu.BucketName
	accessKey := variables.ZoneSetting.Qiniu.AccessKey
	secretKey := variables.ZoneSetting.Qiniu.SecretKey

	mac := qbox.NewMac(accessKey, secretKey)
	cfg := storage.Config{
		Zone:          &storage.ZoneHuanan,
		UseCdnDomains: false,
		UseHTTPS:      false,
	}
	bucketManager := storage.NewBucketManager(mac, &cfg)
	return newname, bucketManager.Move(bucketName, oldname, bucketName, newname, true)
}

func (s *QiniuUploader) BucketDelete(fileNames ...string) error {
	bucketName := variables.ZoneSetting.Qiniu.BucketName
	accessKey := variables.ZoneSetting.Qiniu.AccessKey
	secretKey := variables.ZoneSetting.Qiniu.SecretKey

	mac := qbox.NewMac(accessKey, secretKey)
	cfg := storage.Config{
		Zone:          &storage.ZoneHuanan,
		UseCdnDomains: false,
		UseHTTPS:      false,
	}
	bucketManager := storage.NewBucketManager(mac, &cfg)
	deleteOps := make([]string, 0, len(fileNames))
	for _, fileName := range fileNames {
		deleteOps = append(deleteOps, storage.URIDelete(bucketName, fileName))
	}
	_, err := bucketManager.Batch(deleteOps)
	return err
}
